package com.bw.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TradeOrderBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.function.DorisMapFunction;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author sw
 * @CreateTime 2024-11-21
 * 12.8 交易域下单各窗口汇总表
 */
public class DwsTradeOrderWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeOrderWindow().start(10028,4,
                Constant.DWS_TRADE_ORDER_WINDOW,
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        //清洗数据，计算指标
        SingleOutputStreamOperator<TradeOrderBean> processStream = getProcessStream(dataStreamSource);
        //设置水位线，开窗聚合
        SingleOutputStreamOperator<TradeOrderBean> result = getResult(processStream);
        result.print();
        //写入doris
        result.map(new DorisMapFunction<>())
                .sinkTo(FlinkSinkUtil.getDorisSink("dws_trade_order_window"));
    }

    private static SingleOutputStreamOperator<TradeOrderBean> getResult(SingleOutputStreamOperator<TradeOrderBean> processStream) {
         return processStream.assignTimestampsAndWatermarks(WatermarkStrategy
                        .<TradeOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                        .withTimestampAssigner((event, timestamp) -> event.getTs())
                        .withIdleness(Duration.ofSeconds(5)))
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradeOrderBean>() {
                            @Override
                            public TradeOrderBean reduce(TradeOrderBean x, TradeOrderBean y) throws Exception {
                                x.setOrderUniqueUserCount(x.getOrderUniqueUserCount() + y.getOrderUniqueUserCount());
                                x.setOrderNewUserCount(x.getOrderNewUserCount() + y.getOrderNewUserCount());
                                return x;
                            }
                        },
                        new ProcessAllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                            @Override
                            public void process(ProcessAllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>.Context context, Iterable<TradeOrderBean> iterable, Collector<TradeOrderBean> collector) throws Exception {
                                TradeOrderBean tradeOrderBean = iterable.iterator().next();
                                tradeOrderBean.setStt(DateFormatUtil.tsToDateTime(context.window().getStart()));
                                tradeOrderBean.setEdt(DateFormatUtil.tsToDateTime(context.window().getEnd()));
                                tradeOrderBean.setCurDate(DateFormatUtil.tsToDate(System.currentTimeMillis()));
                                collector.collect(tradeOrderBean);
                            }
                        });
    }

    private static SingleOutputStreamOperator<TradeOrderBean> getProcessStream(DataStreamSource<String> dataStreamSource) {
         return dataStreamSource.map(JSON::parseObject)
                .keyBy(x -> x.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradeOrderBean>() {
                    ValueState<String> lastOrderState;

                    @Override
                    public void open(Configuration parameters) {
                        lastOrderState = getRuntimeContext().getState(
                                new ValueStateDescriptor<>("lastOrderState", String.class));
                    }

                    @Override
                    public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeOrderBean>.Context context, Collector<TradeOrderBean> collector) throws Exception {
                        Long ts = jsonObject.getLong("ts") * 1000;
                        String today = DateFormatUtil.tsToDateTime(ts);
                        String lastOrderValue = lastOrderState.value();
                        // 下单独立用户数
                        Long orderUniqueUserCount = 0L;
                        // 下单新用户数
                        Long orderNewUserCount = 0L;
                        if (!today.equals(lastOrderValue)) {
                            orderUniqueUserCount = 1L;
                            if (lastOrderState == null) {
                                orderNewUserCount = 1L;
                            }
                            lastOrderState.update(today);
                        }
                        if (orderUniqueUserCount == 1) {
                            collector.collect(new TradeOrderBean("", "", "",
                                    orderUniqueUserCount, orderNewUserCount, ts));
                        }
                    }
                });
    }
}
